package cn.seapon.talker;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.seapon.talker.bean.Account;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.net.TalkerNetOperationUtils;
import cn.seapon.talker.utils.Md5Util;

public class LoginActivity extends Activity implements OnClickListener {

	private static final String TAG = "||__LoginActivity__||";

	private static final int LOGIN_SUCCESS = 1;
	private static final int LOGIN_FALED = 0;

	private EditText login_account = null;
	private EditText login_password = null;
	private Button login_button = null;
	private CheckBox remember_me = null;
	private RelativeLayout wait_net_frame = null;
	private Button register = null;

	private Handler hander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			wait_net_frame.setVisibility(View.GONE);
			switch (msg.what) {
			
				case LOGIN_SUCCESS:
					Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(LoginActivity.this,MainActivity.class);
					startActivity(intent);
					break;
	
				case LOGIN_FALED:
					Toast.makeText(LoginActivity.this, "登录失败，请检查用户名或者密码是否正确！", Toast.LENGTH_SHORT).show();
					login_password.setText("");
					break;
	
				default:
					break;
				}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		login_account = (EditText) findViewById(R.id.login_account);
		login_password = (EditText) findViewById(R.id.login_passwd);
		login_button = (Button) findViewById(R.id.login_botton);
		remember_me = (CheckBox) findViewById(R.id.remember_me);
		wait_net_frame = (RelativeLayout) findViewById(R.id.wait_net_layout);
		register = (Button) findViewById(R.id.register);

		makeOutLoginForm();
		
		login_button.setOnClickListener(this);
		register.setOnClickListener(this);
	}

	/**
	 * 设置默认填充
	 */
	private void makeOutLoginForm() {
		Account account = SharedItems.accountDao.getDefault();
		if (account != null) {
			String dftName = account.getName();
			String dftPasswd = account.getPasswd();
			if (TextUtils.isEmpty(dftName)) {
				Log.d(TAG, "用户名为空，密码必须为空!");
				dftPasswd = "";
			} else if (!TextUtils.isEmpty(dftPasswd)) {
				Log.d(TAG, "用户名非空，保存的密码为非空，设置密文!");			
				dftPasswd = "******";
			} else {
				Log.d(TAG, "用户名非空 密码为空，不做处理");
			}
			login_account.setText(dftName);
			login_password.setText(dftPasswd);
		} else {
			Log.e(TAG, "无默认登录的账号,不自动填写表单！");
		}
	}

	public void onClick(View v) {
		final boolean checked = remember_me.isChecked();
		switch (v.getId()) {
		case R.id.login_botton:
			// 登录处理
			wait_net_frame.setVisibility(View.VISIBLE);
			new Thread() {
				
				@Override
				public void run() {
					Message message = Message.obtain();
					String accountName = login_account.getText().toString();
					String passwd = null;
					if ("******".equals(login_password.getText().toString())) {
						Log.d(TAG, "使用默认表单填写的数据，密码是不准确的，从数据库中重新读取！");
						Account account1 = SharedItems.accountDao.getDefault();
						passwd = account1.getPasswd();
					} else {
						Log.d(TAG, "是用户输入的，MD5加密,原密码是"+login_password.getText().toString());
						passwd = Md5Util.makeMD5(login_password.getText().toString());
					}
					
					Log.d(TAG, "登录账户是：" + accountName + "   密码是：" + passwd);
					try {
						if (TalkerNetOperationUtils.loginCheck(accountName, passwd)) {
							message.what = LOGIN_SUCCESS;
							Log.d(TAG, "Checked:" + checked);
							if (checked) {
								//保存密码
								saveLogin(accountName, passwd,true);
							}else {
								saveLogin(accountName, "",false);
							}
							hander.sendMessage(message);
							return ;
						}
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					} 
					message.what = LOGIN_FALED;
					hander.sendMessage(message);
				}
			}.start();
			
			break;

		case R.id.register:
			Intent intent = new Intent(this, RegisterAccountActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	/**
	 * 保存成为默认登录的账户
	 * @param account
	 * @param passwd
	 * @param b 
	 */
	protected void saveLogin(String account, String passwd, boolean b) {
		SharedItems.accountDao.addAccount(new Account(account, passwd, b));
	}

}
